<?php
/**
 * request.class.php
 *
 * Request params wrapper
 *
 * @version:	0.4
 * @package:	core
 * @author:	alex_ez
 * @created:	15 nov 2008
 *
 * @link:	http://src.qfox.ru/
 *
 * @copyright:	(c) 2008 flamebox.ru. All rights reserved.
 */

function trailingslashit($string) {

	return untrailingslashit($string)
		. (strpos($string,'?')===false && preg_match('@\.[a-z0-9]{2,5}$@i',$string)===0
			? '/' : '');

}

function untrailingslashit($string) {
    return rtrim($string, '/');
}

function base_url() {
    $request = request::instance();
    $port = $request->get_port();
    $scheme = $request->get_scheme();

    if($scheme == 'http' && $port == 80
    	|| $scheme == 'https' && $port == 443)
        return sprintf('%s://%s/', $scheme, $request->get_host());

    return sprintf('%s://%s:%d/', $request->get_scheme(), $request->get_host(), $port);
}

function site_url($uri, $rel=false) {
    $base_url = base_url();

	$uri = trim($uri);

	if ($colon = mb_strpos($uri,':')) {
		if (ctype_alnum(mb_substr($uri, 0, $colon-1))) {
			return $uri;
		}
	}

    if(is_array($uri))
        $uri = implode('/', $uri);

	if (strpos($uri,$base_url)===0)
		$uri = substr($uri,strlen($base_url));

    if($uri == '')
        return $rel ? '/' : $base_url;
    else
        return trailingslashit(($rel ? '/' : $base_url) . trim($uri, '/'));
}

function current_url($noquery=false){
	return preg_replace('@^(/ajax)?(.*)(\?.*)$@i',$noquery?'\2':'\2\3',request::instance()->get_uri());
}

function current_ajax_url($noquery=false){
	return '/ajax'.current_url($noquery);
}

function url_compare($a,$b) {
	$a = site_url($a);
	$b = site_url($b);
	if (strpos($a,$b)!==0) return -1;
	return abs( strcmp( site_url($a), site_url($b) ) );
}

function nocache_url($s)
{
	$s = site_url(preg_replace('@\?[0-9]+$@','',$s));
	return $s.(strpos($s,'?')===false ? '?' : '&' ).rand(10000,99999);
}

function inner_url($controller,$method,$data=null,$params=null)
{
	if(func_num_args()==2)
	{
		$data = $method;
		$method = $controller;
		$controller = controller::active_controller();
	}
	
	$r = controller::instance_of($controller)->inner_url($method,$data);
	
	if(is_array($params)&&!empty($params))
		$r = $r . (strpos($r,'?')!==false?'&':'?') . http_build_query($params);

	return $r;
}

